package com.github.ilioili.justdoit.components.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.components.fragment.ToDoListOfTodayFragment;
import com.github.ilioili.justdoit.components.patch.UpdateHelper;
import com.github.ilioili.justdoit.common.AppBaseActivity;
import com.github.ilioili.justdoit.common.config.EventConstants;
import com.github.ilioili.justdoit.common.config.IntentKey;
import com.github.ilioili.justdoit.common.config.UserInfo;
import com.github.ilioili.justdoit.components.fragment.AccomplementFragment;
import com.github.ilioili.justdoit.components.fragment.HabitsTabFragment;
import com.github.ilioili.justdoit.model.pojo.ScheduleEvent;
import com.github.ilioili.justdoit.util.CompatUtil;
import com.github.ilioili.justdoit.widget.SatelliteView;
import com.github.ilioili.justdoit.widget.ScrollPage;
import com.github.ilioili.qqlogin.QqLoginBridgeActivity;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.Layout;
import com.taihe.template.base.util.SizeUtil;
import com.taihe.template.base.util.ToastUtil;

import java.util.Random;

import ht.util.img.Img;


@Layout(R.layout.activity_main)
public class MainActivity extends AppBaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private static final int REQUEST_ADD_HABBIT = 1111;
    @Id(R.id.toolbar)
    private Toolbar toolbar;
    private ToDoListOfTodayFragment toDoListOfTodayFragment;
    private HabitsTabFragment scrollableTabFragment;
    private AccomplementFragment accomplementFragment;
    @Id(R.id.scrollPage)
    private ScrollPage scrollPage;
    @Id(R.id.content_view)
    private View vContentView;
    @Id(R.id.fab)
    private FloatingActionButton floatingActionButton;
    private SatelliteMenu satelliteMenu;
    @Id(R.id.nav_view)
    private NavigationView navigationView;

    private void replaceWithMainFrgment() {
        if (!floatingActionButton.isEnabled()) {
            floatingActionButton.setEnabled(true);
            floatingActionButton.startAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_from_bottom));
        }
        scrollPage.scrollToPage(0);
        setFragmentUserVisibleHint(0);
        getSupportActionBar().setTitle(R.string.menu_today_task);
    }

    private void replaceWithRoutineFrgment() {
        if (!floatingActionButton.isEnabled()) {
            floatingActionButton.setEnabled(true);
            floatingActionButton.startAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_from_bottom));
        }
        scrollPage.scrollToPage(1);
        setFragmentUserVisibleHint(1);
        getSupportActionBar().setTitle(R.string.menu_target_and_task);
    }

    private void setFragmentUserVisibleHint(int index) {
        int i = 0;
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            fragment.setUserVisibleHint(i++ == index);
        }
    }

//    private void replaceWithAccomplementFrgment() {
//        Animation animation = AnimationUtils.loadAnimation(this, R.anim.drop_to_bottom);
//        animation.setFillAfter(true);
//        floatingActionButton.setEnabled(false);
//        floatingActionButton.startAnimation(animation);
////        floatingActionButton.setImageResource(R.drawable.ic_expand_detail_24dp);
//        scrollPage.scrollToPage(2);
//        setFragmentUserVisibleHint(2);
//        getSupportActionBar().setTitle(R.string.menu_achievement);
//    }

    public void setToolbarColor(int color) {
        vContentView.setBackgroundColor(color);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(R.string.menu_today_task);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                if (null == scrollableTabFragment) {
                    scrollableTabFragment = HabitsTabFragment.newInstance();
                    scrollableTabFragment.setUserVisibleHint(false);
                    getSupportFragmentManager().beginTransaction().add(R.id.scrollPage, scrollableTabFragment).commitAllowingStateLoss();
                }
//                if (null == accomplementFragment) {
//                    accomplementFragment = AccomplementFragment.newInstance();
//                    getSupportFragmentManager().beginTransaction().add(R.id.scrollPage, accomplementFragment).commitAllowingStateLoss();
//                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
        postWhenIdle(new Runnable() {
            @Override
            public void run() {
                toDoListOfTodayFragment = ToDoListOfTodayFragment.newInstance();
                getSupportFragmentManager().beginTransaction().add(R.id.scrollPage, toDoListOfTodayFragment).commitAllowingStateLoss();
            }
        });
        floatingActionButton.setVisibility(View.GONE);
        floatingActionButton.post(new Runnable() {
            @Override
            public void run() {
                Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.popup_from_bottom);
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        floatingActionButton.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                floatingActionButton.startAnimation(animation);
            }
        });

        UpdateHelper.checkUpdate(this);
    }

    private void loginAndUpdateInfo() {
        QqLoginBridgeActivity.login(this, new QqLoginBridgeActivity.OnUserInfoListener() {
            @Override
            public void onUserInfoObtained(String name, String iconUrl, String id) {
                UserInfo.setName(name);
                UserInfo.setIconUrl(iconUrl);
                UserInfo.setIsLogin(true);
                UserInfo.setUserId(id);
                setIconAndNameAndMotto();
            }
        });
    }

    private void setIconAndNameAndMotto() {
        TextView tvName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.tv_name);
        ImageView ivIcon = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.iv_icon);
        TextView tvMotto = (TextView) navigationView.getHeaderView(0).findViewById(R.id.tv_motto);
        String[] mottos = getResources().getStringArray(R.array.MenuTipsOfTheDay);
        tvMotto.setText(mottos[new Random(System.currentTimeMillis()).nextInt(mottos.length)]);
        if (UserInfo.isLogin()) {
            tvName.setText(UserInfo.getName());
            Img img = new Img(getCacheDir(), getFilesDir(), UserInfo.getIconUrl());
            img.setRadius(50);
            img.setImageViewAsync(ivIcon);
        } else {
            tvName.setText(R.string.ClickToLogin);
            ivIcon.setImageResource(R.drawable.ic_account_circle_24dp);
        }
        navigationView.setNavigationItemSelectedListener(this);
        View.OnClickListener l = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserInfo.isLogin()) {
                    loginAndUpdateInfo();
                } else {
                    startActivity(ProfileActivity.newIntent(MainActivity.this));
                    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                }
            }
        };
        ivIcon.setOnClickListener(l);
        tvName.setOnClickListener(l);
    }

    private void rotateFloatingButton() {
        Animation rotateAnimation = new RotateAnimation(0, -45, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(400);
        rotateAnimation.setInterpolator(new DecelerateInterpolator());
        rotateAnimation.setFillAfter(true);
        floatingActionButton.startAnimation(rotateAnimation);
    }

    private void rotateBackFloatingButton() {
        Animation rotateAnimation = new RotateAnimation(-45, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(400);
        rotateAnimation.setInterpolator(new DecelerateInterpolator());
        rotateAnimation.setFillAfter(true);
        floatingActionButton.startAnimation(rotateAnimation);
    }

    public void onClickFloatingActionButton(View v) {
        if (null == satelliteMenu) {
            satelliteMenu = new SatelliteMenu();
        }
        rotateFloatingButton();
        satelliteMenu.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        setIconAndNameAndMotto();
        if (scrollPage.getCurrentPageIndex() != 2)
            floatingActionButton.startAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_from_bottom));
    }

    @Override
    public void onPause() {
        super.onPause();
        if (scrollPage.getCurrentPageIndex() != 2) {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.drop_to_bottom);
            animation.setFillAfter(true);
            floatingActionButton.startAnimation(animation);
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (scrollPage.getCurrentPageIndex() != 0) {
            replaceWithMainFrgment();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_about_app) {
            startActivity(AboutActivity.newIntent(this));
            overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        } else if (id == R.id.menu_settings) {
            startActivity(SettingsActivity.newIntent(this));
            overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        } else if (id == R.id.menu_arrange) {
            startActivity(ScheduleEventTabActivity.newIntent(this));
            overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        } else if (id == R.id.menu_quadrant) {
            startActivity(QuadrantActivity.newIntent(this));
            overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        } else if (id == R.id.menu_search) {
            startActivity(SearchActivity.newIntent(this));
            overridePendingTransition(0, 0);
        } else if (id == R.id.menu_category) {
            startActivity(CategoryTabActivity.newIntent(this));
            overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_todo) {
            replaceWithMainFrgment();
        } else if (id == R.id.nav_routine) {
            replaceWithRoutineFrgment();
        } else if (id == R.id.nav_share) {
            Uri uri = Uri.parse("market://details?id=" + getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if (id == R.id.nav_qq) {
            jumpToQqOrFacebook();
        } else if (id == R.id.nav_talk) {
            jumpToQqGroup();
        } else if (id == R.id.nav_pay) {
            jumpToAlipay();
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_ADD_HABBIT) {
            ScheduleEvent scheduleEvent = (ScheduleEvent) data.getSerializableExtra(IntentKey.GET_HABBIT);
            Snackbar.make(floatingActionButton, "创建[" + scheduleEvent.name + "]成功", Snackbar.LENGTH_SHORT).show();
        }
    }


    private void jumpToQqGroup() {
//            String url="mqqwpa://im/chat?chat_type=internal&uin=284821731";
        String url = "mqqapi://card/show_pslcard?src_type=internal&uin=284821731&card_type=group";
//            String url = "mqqwpa://im/chat?chat_type=crm&uin=938039033";//企业客服号
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        if (null == intent.resolveActivity(getPackageManager())) {
            ToastUtil.showShortToast(getString(R.string.qq_not_installed));
        } else {
            startActivity(intent);
        }
    }

    private void jumpToQqOrFacebook() {
        String url = "mqqwpa://im/chat?chat_type=wpa&uin=136351754";
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        if (null != intent.resolveActivity(getPackageManager())) {
            startActivity(intent);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/100012517003083"));
            if (null == intent.resolveActivity(getPackageManager())) {
                ToastUtil.showShortToast(getString(R.string.not_social_find_error));
            } else {
                startActivity(intent);
            }
        }
    }

    private void jumpToAlipay() {
        Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/apn5aqr0qhfzu5y862");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        if (null == intent.resolveActivity(getPackageManager())) {
            ToastUtil.showShortToast(getString(R.string.alipay_not_installed));
        } else {
            startActivity(intent);
        }
    }

    class SatelliteMenu {

        SatelliteView satelliteView;
        private final View.OnClickListener onClickDetail = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                rotateBackFloatingButton();
                int[] loc = new int[2];
                v.getLocationInWindow(loc);
                startActivity(DetailActivity.newIntent(MainActivity.this, scrollableTabFragment.getCurrent(), loc[0] + v.getWidth() / 2, loc[1] + v.getHeight() / 2));
                overridePendingTransition(0, 0);
            }
        };
        private final View.OnClickListener onClickNewTarget = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                rotateBackFloatingButton();
                int[] loc = new int[2];
                floatingActionButton.getLocationInWindow(loc);
                startActivityForResult(CreateOrModifyActivity.newIntent(MainActivity.this, EventConstants.TYPE_TARGET, loc[0] + floatingActionButton.getWidth() / 2, loc[1] + floatingActionButton.getHeight() / 2, CompatUtil.getColor(MainActivity.this, R.color.colorAccent)), REQUEST_ADD_HABBIT);
                overridePendingTransition(0, 0);
            }
        };
        private final View.OnClickListener onClickNewEvent = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                rotateBackFloatingButton();
                int[] loc = new int[2];
                floatingActionButton.getLocationInWindow(loc);
                startActivityForResult(CreateOrModifyActivity.newIntent(MainActivity.this, EventConstants.TYPE_EVENT, loc[0] + floatingActionButton.getWidth() / 2, loc[1] + floatingActionButton.getHeight() / 2, CompatUtil.getColor(MainActivity.this, R.color.colorAccent)), REQUEST_ADD_HABBIT);
                overridePendingTransition(0, 0);
            }
        };
        private final View.OnClickListener onClickNewHabit = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                satelliteView.collapse();
                rotateBackFloatingButton();
                int[] loc = new int[2];
                floatingActionButton.getLocationInWindow(loc);
                startActivityForResult(CreateOrModifyActivity.newIntent(MainActivity.this, EventConstants.TYPE_HABIT, loc[0] + floatingActionButton.getWidth() / 2, loc[1] + floatingActionButton.getHeight() / 2, CompatUtil.getColor(MainActivity.this, R.color.colorAccent)), REQUEST_ADD_HABBIT);
                overridePendingTransition(0, 0);
            }
        };

        private SatelliteMenu() {
            satelliteView = (SatelliteView) LayoutInflater.from(MainActivity.this).inflate(R.layout.satellite_add, null);
            satelliteView.findViewById(R.id.add_event).setOnClickListener(onClickNewEvent);
            satelliteView.findViewById(R.id.add_target).setOnClickListener(onClickNewTarget);
            satelliteView.findViewById(R.id.add_habit).setOnClickListener(onClickNewHabit);
            satelliteView.findViewById(R.id.add_detail).setOnClickListener(onClickDetail);
            satelliteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    satelliteView.collapse();
                    rotateBackFloatingButton();
                }
            });
            satelliteView.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                        satelliteView.clearFocus();
                        satelliteView.collapse();
                        rotateBackFloatingButton();
                        return true;
                    }
                    return false;
                }
            });
        }

        public void show() {
            int[] loc = new int[2];
            floatingActionButton.getLocationOnScreen(loc);
            satelliteView.expand(floatingActionButton, false, SizeUtil.dpToPx(100, MainActivity.this), 180, 270);
            if (scrollPage.getCurrentPageIndex() == 1 && null != scrollableTabFragment.getCurrent()) {
                satelliteView.findViewById(R.id.add_detail).setVisibility(View.VISIBLE);
            } else {
                satelliteView.findViewById(R.id.add_detail).setVisibility(View.GONE);
            }
        }


    }
}
